<template>
  <div class="search">
    <el-form
      :model="searchForm"
      :label-width="searchConfig.labelWidth ?? '80px'"
      size="large"
      ref="formRef"
    >
      <el-row>
        <template v-for="item in searchConfig.formItems" :key="item.prop">
          <el-col :span="8">
            <el-form-item :label="item.label" :prop="item.prop">
              <!-- <component
                :is="`el-${item.type}`"
                v-bind="item"
                v-model="searchForm[item.prop]"
                :placeholder="item.placeholder"
              ></component> -->
              <template v-if="item.type === 'input'">
                <el-input
                  v-model="searchForm[item.prop]"
                  :placeholder="item.placeholder"
                ></el-input>
              </template>
              <template v-if="item.type === 'select'">
                <el-select v-model="searchForm[item.prop]" :placeholder="item.placeholder">
                  <el-option
                    v-for="option in item.options"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  ></el-option>
                </el-select>
              </template>
              <template v-if="item.type === 'date-picker'">
                <el-date-picker
                  v-model="searchForm[item.prop]"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </template>
            </el-form-item>
          </el-col>
        </template>
      </el-row>
    </el-form>
    <div class="btns">
      <el-button size="large" @click="handleQueryClick">查询</el-button>
      <el-button size="large" type="primary" @click="handleResetClick">重置</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { ElForm } from 'element-plus'
import { reactive, ref } from 'vue'

// 定义自定义事件(emit抛发)
const emit = defineEmits(['queryClick'])
// 接收的属性
interface IProps {
  labelWidth?: string
  searchConfig: {}
}
const props = defineProps<IProps>()

// 定义form的数据
const initialForm: any = {}
for (const item of props.searchConfig.formItems) {
  initialForm[item.prop] = item.initialValue ?? ''
}
const searchForm = reactive(initialForm)

const formRef = ref<InstanceType<typeof ElForm>>()
function handleResetClick() {
  formRef.value?.resetFields()

  // 重置后，重新发送事件
  emit('resetClick')
}

// 发送事件
function handleQueryClick() {
  emit('queryClick', searchForm)
}
</script>

<style scoped lang="less">
.search {
  padding: 20px;
  background-color: #fff;
  .el-form-item {
    padding: 20px 30px;
    margin-bottom: 0;
  }
  .btns {
    text-align: right;
    height: 36px;
    padding: 0 50px 10px 0;
  }
}
</style>
